package com.tianji.promotion.lock;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class MyLockAspect {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private LogFactory logFactory;

    @Around("@annotation(lock)")
    public Object proceed(ProceedingJoinPoint pjp, DistributeLock lock) throws Throwable {
        log.info("LockAspect start");
        // 获取锁，从工厂中获取锁
        RLock rlock = logFactory.getLock(lock.lockType(), lock.lockName());
        // 尝试获取锁
        MyLockStrategy myLockStrategy = lock.lockStrategy();
        boolean locked = myLockStrategy.tryLock(rlock, lock);
        //boolean locked = rlock.tryLock(lock.waitTime(), lock.leaseTime(), lock.timeUnit());
        if(!locked){
            // throw new BizIllegalException("非法请求，请求太频繁");
            // 说明没获取到锁，直接返回，不做业务逻辑
            return null;
        }
        Object result = null;
        try{
            // 继续执行业务逻辑
            result = pjp.proceed();
        }finally {
            // 释放锁
            rlock.unlock();
        }
        return result;
    }
}
